var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var request = require('request')
var fs = require("fs");
var path = require("path");
var log4js = require('log4js');

//递归创建目录 同步方法  
function mkdirsSync(dirname) {  
    //console.log(dirname);  
    if (fs.existsSync(dirname)) {  
        return true;  
    } else {  
        if (mkdirsSync(path.dirname(dirname))) {  
            fs.mkdirSync(dirname);  
            return true;  
        }  
    }  
  }  

  //日志模块
var logPath = './logs';
mkdirsSync(logPath);
logPath += '/log.txt';
log4js.configure({
  appenders: {
    console : { type: 'console' }, //控制台输出
    index :{
      type: 'file', //文件输出
      filename: logPath, 
      maxLogSize: 1024*1024*10,
      backups:100
    }
  },
  categories: {
    default: { appenders: ['index'], level: 'info' }
  },
  replaceConsole: true
});
var logger = log4js.getLogger('index');

//启动http服务器
var app = express();

app.use(log4js.connectLogger(logger, {level:log4js.levels.INFO}));
app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

/**
 * 下载图片
 * @param {string} imgPath 存放图片的路径
 * @param {string} url 图片的 URL 地址
 */
function downloadImg(imgPath, url) {
    https.get(url, function(res) {
        var data = '';

        res.setEncoding('binary');

        res.on('data', function(chunk) {
            data += chunk;
        });

        res.on('end', function() {
            fs.writeFile(imgPath, data, 'binary', function(err) {
                if (err) {
                    return console.log(err);
                }
                console.log('Image downloaded:', url);
            });
        });
    }).on('error', function(err) {
        console.log(err);
    });
}

app.get('/sendpic', function (req, res) {
    //logger.info(req.originalUrl);
    var name = req.query.name;
    var url  = req.query.url;
    console.log('name:'+name+'  url:'+url);
    if(name.length == 0 || url.length == 0) {
        res.status(400).send('error param');
        return;
    }

    var dstpath = 'd://111';
    mkdirsSync(dstpath);
    //request(url).pipe(fs.createWriteStream(dstpath+'/'+name));
    downloadImg(dstpath+'/'+name, url);
    res.status(200).send(dstpath+'/'+name);
 });

 var server = app.listen(8000, function () {
 
    var host = server.address().address;
    var port = server.address().port;
   
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
   
  })